/*
 *    Copyright (c) 2018-2025, lengleng All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: lengleng (wangiegie@gmail.com)
 */

package com.dy.yunying.biz.controller.hongbao;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.dy.yunying.api.dto.SonGameDto;
import com.dy.yunying.api.entity.GameRole;
import com.dy.yunying.api.entity.WanRechargeOrder;
import com.dy.yunying.api.entity.WanUser;
import com.dy.yunying.api.entity.hongbao.HbActivityRoleInfo;
import com.dy.yunying.api.entity.hongbao.HbWithdrawRecord;
import com.dy.yunying.api.req.hongbao.HbWithdrawRecordRejectReq;
import com.dy.yunying.api.req.hongbao.HbWithdrawRecordReq;
import com.dy.yunying.api.vo.HbWithdrawRecordVO;
import com.dy.yunying.api.vo.hongbao.HbWithdrawRecordDetailVo;
import com.dy.yunying.biz.service.hongbao.ActivityService;
import com.dy.yunying.biz.service.hongbao.HbActivityRoleInfoService;
import com.dy.yunying.biz.service.hongbao.HbUserWithdrawAccountService;
import com.dy.yunying.biz.service.hongbao.HbWithdrawRecordService;
import com.dy.yunying.biz.service.manage.GameRoleService;
import com.dy.yunying.biz.service.manage.GameService;
import com.dy.yunying.biz.service.manage.ParentGameService;
import com.dy.yunying.biz.service.manage.WanRechargeOrderService;
import com.dy.yunying.biz.service.manage.WanUserService;
import com.dy.yunying.biz.service.raffle.RaffleReceiveRecordService;
import com.dy.yunying.biz.utils.DateUtils;
import com.google.common.collect.Lists;
import com.pig4cloud.pig.admin.api.feign.RemoteUserService;
import com.pig4cloud.pig.api.util.NoRepeatSubmit;
import com.pig4cloud.pig.common.core.exception.BusinessException;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.log.annotation.SysLog;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.net.URLEncoder;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 提现审核
 *
 * @author zhuxm
 * @date 2021-10-28 20:11:29
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/withdrawAuth")
@Api(value = "withdrawAuth", tags = "活动管理-提现审核")
@Slf4j
public class WithdrawAuthController {

	private final HbWithdrawRecordService hbWithdrawRecordService;
	private final HbUserWithdrawAccountService hbUserWithdrawAccountService;
	private final HbActivityRoleInfoService hbActivityRoleInfoService;
	private final RaffleReceiveRecordService raffleReceiveRecordService;

	private final RemoteUserService remoteUserService;

	private final ParentGameService parentGameService;

	private final GameService gameService;

	private final ActivityService activityService;

	private final GameRoleService gameRoleService;

	private final WanRechargeOrderService wanRechargeOrderService;

	private final WanUserService wanUserService;

	@ApiOperation(value = "提现审核列表", notes = "提现审核列表")
	@RequestMapping("/selectInvestRecordPage")
	public R selectInvestRecordPage(@Valid @RequestBody HbWithdrawRecordReq req) {
		try {
			return R.ok(hbWithdrawRecordService.selectRecordPage(req));
		} catch (Exception e) {
			log.error("活动管理-提现审核列表-接口：{}", e.getMessage());
			return R.failed("接口异常，请联系管理员");
		}
	}



	@ApiOperation(value = "提现驳回", notes = "提现驳回")
	@SysLog("提现驳回")
	@PostMapping("/reject")
	@PreAuthorize("@pms.hasPermission('hongbao_withdrawauth_reject')")
	@NoRepeatSubmit(lockTime = 3000)
	public R reject(@Valid @RequestBody HbWithdrawRecordRejectReq req) {
		try {
			if(StringUtils.isBlank(req.getRejectReason())){
				return R.failed("驳回原因不能为空");
			}

			return R.ok(hbWithdrawRecordService.reject(req));
		} catch (Exception e) {
			log.error("活动管理-提现驳回-接口：{}", e.getMessage());
			return R.failed("接口异常，请联系管理员");
		}
	}

	@ApiOperation(value = "提现通过", notes = "提现通过")
	@SysLog("提现通过")
	@PostMapping("/pass")
	@PreAuthorize("@pms.hasPermission('hongbao_withdrawauth_pass')")
	@NoRepeatSubmit(lockTime = 3000)
	public R pass(@RequestBody HbWithdrawRecordRejectReq req) {
		try {
			if (Objects.isNull(req.getId())){
				return R.failed("提现记录ID不能为空");
			}
			return hbWithdrawRecordService.pass(req);
		} catch (Exception e) {
			log.error("活动管理-提现驳回-接口：{}", e.getMessage());
			return R.failed("接口异常，请联系管理员");
		}
	}

	@ApiOperation(value = "批量提现通过", notes = "批量提现通过")
	@SysLog("批量提现通过")
	@PostMapping("/batchReviewer")
	@PreAuthorize("@pms.hasPermission('hongbao_withdrawauth_batch')")
	@NoRepeatSubmit(lockTime = 3000)
	public R batchReviewer(@RequestBody HbWithdrawRecordRejectReq req) {
		try {
			if (StringUtils.isBlank(req.getIds())){
				return R.failed("提现记录ID不能为空");
			}
			if (StringUtils.isBlank(req.getReviewerType())){
				return R.failed("审核类型不能为空");
			}
			if ("2".equals(req.getReviewerType())){
				if(StringUtils.isBlank(req.getRejectReason())){
					return R.failed("驳回原因不能为空");
				}
			}
			return hbWithdrawRecordService.batchReviewer(req);
		} catch (Exception e) {
			log.error("活动管理-提现驳回-接口：{}", e.getMessage());
			return R.failed("接口异常，请联系管理员");
		}
	}


	@ApiOperation(value = "提现审核详情", notes = "提现审核详情")
	@RequestMapping("/detail")
	@NoRepeatSubmit(lockTime = 3000)
	public R detail(Long id) {
		try {
			if(id == null){
				return R.failed("提现id不能为空");
			}
			HbWithdrawRecord hbWithdrawRecord = hbWithdrawRecordService.getById(id);
			if(hbWithdrawRecord == null){
				return R.failed("该提现记录不存在");
			}
			Long activityId = hbWithdrawRecord.getActivityId();
			Long userId = hbWithdrawRecord.getUserId();
			String userName = hbWithdrawRecord.getUsername();
			Integer areaId = hbWithdrawRecord.getAreaId();
			String roleId = hbWithdrawRecord.getRoleId();
			Integer parentGameId = hbWithdrawRecord.getParentGameId();
			Integer gameId = hbWithdrawRecord.getGameId();
			//收款账号、角色等级、角色累充()、注册时间、创角时间、最后付费时间、最后登录时间、登录IP
			//角色等级：当前等级
			//角色累充(元)：活动期间累计充值
			//注册时间：账号注册时间
			//创角时间：角色创建时间
			//最后付费时间：角色最后付费时间
			//最后登录时间：角色最后登录时间
			//登录IP：角色最后登录IP
			GameRole gameRole = gameRoleService.getOne(Wrappers.<GameRole>query()
					.lambda().eq(GameRole::getUserId, userId).eq(GameRole::getPgameId, parentGameId)
					.eq(GameRole::getAreaId, areaId).eq(GameRole::getRoleId, roleId).orderByDesc(GameRole::getRoleLevel).select(GameRole::getRoleLevel, GameRole::getCreateRoleTime, GameRole::getLoginTime, GameRole::getLoginIp).last("LIMIT 1"));

			HbActivityRoleInfo hbActivityRoleInfo = hbActivityRoleInfoService.getOne(Wrappers.<HbActivityRoleInfo>query()
					.lambda().eq(HbActivityRoleInfo::getActivityId, activityId)
					.eq(HbActivityRoleInfo::getUserId, userId)
					.eq(HbActivityRoleInfo::getPgameId, parentGameId)
					.eq(HbActivityRoleInfo::getAreaId, areaId)
					.eq(HbActivityRoleInfo::getRoleId, roleId)
					.orderByDesc(HbActivityRoleInfo::getTotalIncome)
					.select(HbActivityRoleInfo::getTotalRechargeAmount).last("LIMIT 1"));

			//
			List<WanRechargeOrder> orderList = wanRechargeOrderService.list(Wrappers.<WanRechargeOrder>query()
					.lambda().eq(WanRechargeOrder::getAccount, userName)
					.eq(WanRechargeOrder::getAreaid, areaId).eq(WanRechargeOrder::getGrole, roleId).orderByDesc(WanRechargeOrder::getPaytime).select(WanRechargeOrder::getPaytime, WanRechargeOrder::getGameid));
			log.info("orderList:{}", JSON.toJSONString(orderList));
			//根子主游戏查出所有的子游戏
			List<SonGameDto> sonGames = gameService.getAutoPackListByPgid(parentGameId.longValue());
			Set<Long> gameIds = sonGames.stream().map(SonGameDto::getGameId).collect(Collectors.toSet());

			log.info("gameIds:{}", JSON.toJSONString(gameIds));
			//根据此父游戏下的所有子游戏进行过滤
			List<WanRechargeOrder> realOrderList = orderList.stream().filter(order -> {
				Long orderGameId = order.getGameid();
				log.info("orderGameId:{}", orderGameId);
				log.info("flag:{}", CollectionUtils.isNotEmpty(gameIds) && gameIds.contains(orderGameId));
				if (CollectionUtils.isNotEmpty(gameIds) && gameIds.contains(orderGameId)){
					return true;
				}else{
					return false;
				}
			}).collect(Collectors.toList());

			log.info("realOrderList:{}", JSON.toJSONString(realOrderList));
			log.info("isEmpty:{}", CollectionUtils.isEmpty(realOrderList));
			log.info("paytime:{}", CollectionUtils.isEmpty(realOrderList) ? null : realOrderList.get(0).getPaytime());

			WanUser wanUser = wanUserService.getOne(Wrappers.<WanUser>query()
					.lambda().eq(WanUser::getUserid, userId).select(WanUser::getRegtime).last("LIMIT 1"));


			HbWithdrawRecordDetailVo detail= new HbWithdrawRecordDetailVo();
			detail.setCreateRoleTime(gameRole == null ? null : gameRole.getCreateRoleTime());
			detail.setLoginIp(gameRole == null ? null : gameRole.getLoginIp());
			detail.setLoginTime(gameRole == null ? null : gameRole.getLoginTime());
			detail.setPayTime(CollectionUtils.isEmpty(realOrderList) ? null : realOrderList.get(0).getPaytime());
			detail.setRegtime(wanUser == null ? null : wanUser.getRegtime());
			detail.setRoleLevel(gameRole == null ? null : gameRole.getRoleLevel());
			detail.setTotalRechargeAmount(hbActivityRoleInfo == null ? null : hbActivityRoleInfo.getTotalRechargeAmount());
			return R.ok(detail);
		} catch (Exception e) {
			log.error("活动管理-提现审核列表-接口：{}", e.getMessage());
			return R.failed("接口异常，请联系管理员");
		}
	}

	/**
	 * 提现审核数据导出
	 *
	 * @param req
	 * @return
	 */
	@PostMapping("/excelExport")
	public void export(@RequestBody HbWithdrawRecordReq req, HttpServletResponse response) {
		String sheetName = "提现审核";
		Long maxSize=9999999L;
		req.setCurrent(1L);
		req.setSize(maxSize);
		try {
			IPage<HbWithdrawRecord> page = hbWithdrawRecordService.selectRecordPage(req);
			List<HbWithdrawRecordVO> hbActiveHbDrawVoList=Lists.newArrayList();
			List<HbWithdrawRecord> list = page.getRecords();
             if(CollectionUtils.isNotEmpty(list)){
				 list.forEach(s->{
					 HbWithdrawRecordVO hbActiveHbDrawVo=new HbWithdrawRecordVO();
					 BeanUtils.copyProperties(s,hbActiveHbDrawVo);
					 hbActiveHbDrawVoList.add(hbActiveHbDrawVo);
				 });
			 }
			response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
			response.setCharacterEncoding("utf-8");
			String fileName = URLEncoder.encode("提现审核-" + DateUtils.getCurrentTimeNoUnderline(), "UTF-8").replaceAll("\\+", "%20");
			response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
			response.setHeader("file-name", fileName);
			//设置excel宽度自适应
			ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()).build();
			// 创建sheet并设置动态标题

			WriteSheet detailSheet = EasyExcel.writerSheet(0, sheetName).head(HbWithdrawRecordVO.class).build();
			// 向sheet中写入数据，将值按照动态顺序进行处理后放入
			excelWriter.write((List<HbWithdrawRecordVO>) hbActiveHbDrawVoList,detailSheet);
			// 数据下载，完成后会自动关闭流
			excelWriter.finish();

		} catch (Exception e) {
			log.error("提现审核数据数据导出异常：{}", e.getMessage());
			throw new BusinessException("提现审核数据数据导出异常，请稍后重试");

		}


	}
}
